package indi.liangli.registry;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Op;


public class RegistryZkImpl  implements IRegistryCenter{

    CuratorFramework curatorFramework;
    //代码块构造curator 实例
    {
        //配置连接超时时间为5秒 ，衰减重试
        curatorFramework = CuratorFrameworkFactory.builder().sessionTimeoutMs(5000)
              .connectString(ZKConfig.CONNECT_STR).retryPolicy(new ExponentialBackoffRetry(1000,3))
              .namespace("registry").build();
        curatorFramework.start();
    }

    //服务注册 把服务统一管理在namespace = registry下
    @Override
    public void registry(String serviceName, String serviceAddress) {
        //所有的serviceName 需要加路径 /
        String servicePath = "/"+serviceName;
        try {
            //服务节点不存在先创建 包含父节点一起
            if(curatorFramework.checkExists().forPath(servicePath) == null){
                curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT)
                        .forPath(servicePath);
            }
            //把服务对应的地址 注解为临时节点，应用挂掉 ，服务自动删除
            String addressPath = servicePath+"/"+serviceAddress;
            curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath(addressPath);
            System.out.println("服务注册成功 。。。");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
